package com.colt.contentcenter.sentineldemo;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: content-center
 * @description: xixi
 * @author: colt
 * @create: 2020-06-05 16:00
 **/
@Component
public class MyUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
        ErrorMsg msg = null;
        if (ex instanceof FlowException){
            msg = ErrorMsg.builder()
                    .code(102)
                    .msg("限流异常").build();
        }else if (ex instanceof ParamFlowException){
            msg = ErrorMsg.builder()
                    .code(103)
                    .msg("热点参数异常").build();
        }else if (ex instanceof DegradeException) {
            msg = ErrorMsg.builder()
                    .code(104)
                    .msg("降级异常").build();
        }else if (ex instanceof SystemBlockException){
            msg = ErrorMsg.builder()
                    .code(105)
                    .msg("系统规则异常").build();
        }else if (ex instanceof AuthorityException){
            msg = ErrorMsg.builder()
                    .code(106)
                    .msg("授权规则异常").build();
        }else {
            msg = ErrorMsg.builder()
                    .code(107)
                    .msg("其他异常").build();
        }
        //http状态码
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type","application/json;charSet=utf-8");
        response.setContentType("application/json;charSet=utf-8");
        //spring mvc自带的json操作工具 ,jackson,将json字符串转成对象,也可反转
        new ObjectMapper()
                .writeValue(response.getWriter(),msg);

    }
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class ErrorMsg{
    private String  msg;
    private Integer code;

}